package org.example;

import javax.swing.*;
import java.awt.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;

public class MigrationProgressMonitor extends JPanel {
    private JProgressBar progressBar;
    private JLabel statusLabel;
    private JTextArea logArea;
    private AtomicInteger recordsProcessed = new AtomicInteger(0);
    private int totalRecords;

    public MigrationProgressMonitor(int totalRecords) {
        this.totalRecords = totalRecords;
        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout(5, 5));
        
        // 进度条部分
        JPanel progressPanel = new JPanel(new BorderLayout(5, 5));
        progressBar = new JProgressBar(0, 100);
        progressBar.setStringPainted(true);
        statusLabel = new JLabel("准备开始...");
        
        progressPanel.add(statusLabel, BorderLayout.NORTH);
        progressPanel.add(progressBar, BorderLayout.CENTER);
        
        // 日志区域
        logArea = new JTextArea();
        logArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(logArea);
        
        add(progressPanel, BorderLayout.NORTH);
        add(scrollPane, BorderLayout.CENTER);
    }

    public void updateProgress(int recordsProcessed) {
        this.recordsProcessed.addAndGet(recordsProcessed);
        int percentage = (int) ((double) this.recordsProcessed.get() / totalRecords * 100);
        progressBar.setValue(percentage);
        statusLabel.setText("已处理 " + this.recordsProcessed.get() + " / " + totalRecords + " 条记录 (" + percentage + "%)");
        
        // 自动滚动到底部
//        SwingUtilities.invokeLater(() -> {
//            JScrollBar vertical = scrollPane.getVerticalScrollBar();
//            vertical.setValue(vertical.getMaximum());
//        });
    }

    public void logMessage(String message) {
        logArea.append(message + "\n");
    }

    public void migrationComplete() {
        progressBar.setValue(100);
        statusLabel.setText("数据迁移完成！共处理 " + totalRecords + " 条记录");
        logMessage("迁移完成时间: " + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
    }

    public void migrationFailed(String errorMessage) {
        statusLabel.setText("数据迁移失败: " + errorMessage);
        logMessage("错误发生时间: " + LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME) + ", 错误信息: " + errorMessage);
    }
}